package com.csx.framework.springboot.sample.mvc.exception;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/8/16 周三 16:19
 */

/**
 * <p>真正起作用的就是{@link ExceptionHandlerExceptionResolver#doResolveHandlerMethodException(HttpServletRequest, HttpServletResponse, HandlerMethod, Exception)}</p>
 * <p>其会扫描标注了 @ExceptionHandler注解的方法，将其作为处理异常的方法进行调用</p>
 * <p>优先级低于 {@link CustomHandlerExceptionResolver} 这种自定义的 {@link HandlerExceptionResolver}</p>
 * <p>当同时存在 @ExceptionHandler 注解标注的方法 和 CustomHandlerExceptionResolver 处理器时，如果处理同一种异常，则以后者为准。(其实就是遍历，最后的处理器返回的结果为最终结果)</p>
 * <p>如果设置的处理器处理后返回一个 viewName,则DispatcherServlet会拿着该viewName去ErrorController中找对应名称的handler去处理</p>
 */
@RestControllerAdvice
public class CustomExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(CustomException.class)
    public String handleCustomException(CustomException exception) {
        return "customExceptionHandler handle customException";
    }


    @ExceptionHandler(Exception.class)
    public String handleException(Exception exception) {
        return "customExceptionHandler handle customException";
    }
}

